package com.health.viewscontrols.tjbg.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.health.R;
import com.health.tablebean.SBCL_DATA;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.tjbg.MyMarkerView;
import com.health.viewscontrols.tjbg.base.BaseFragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * author : xiaoxin
 * date   : 2020/12/21 11:52
 * desc   :
 * update :
 */
public class XueYaFragment extends BaseFragment implements OnChartValueSelectedListener {

    private static final String TAG = "XueYaFragment";

    //x y 轴数据 月
    private List<String> xDayData = new ArrayList<>();
    //高压
    private List<String> yDayData = new ArrayList<>();
    //低压
    private List<String> lDayData = new ArrayList<>();

    private LineChart lineChart;

    private TextView tv_tjbg_no_data;
    String strWhere = "IDCARD = '" + NovaApplication.getUserInfo().getIDCARD() + "'";

    public static XueYaFragment newInstance() {

        XueYaFragment fragment = new XueYaFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_chat;
    }

    @Override
    protected void initView(View view) {
        lineChart = view.findViewById(R.id.linechart);
        tv_tjbg_no_data = view.findViewById(R.id.tv_tjbg_no_data);
    }

    @Override
    protected void initData() {

        initChartView();

        try {
            List<SBCL_DATA> list1 = NovaApplication.fdbmanger.findAllByWhere(SBCL_DATA.class,
                    strWhere + " AND CL_TYPE = '高压' ORDER BY CL_TIME DESC");
            List<SBCL_DATA> list2 = NovaApplication.fdbmanger.findAllByWhere(SBCL_DATA.class,
                    strWhere + " AND CL_TYPE = '低压' ORDER BY CL_TIME DESC");

            if (list1 == null || list1.size() <= 0) {
                lineChart.setVisibility(View.GONE);
                tv_tjbg_no_data.setVisibility(View.VISIBLE);
                tv_tjbg_no_data.setText("暂无血压体检数据");
            } else {
                lineChart.setVisibility(View.VISIBLE);
                tv_tjbg_no_data.setVisibility(View.GONE);
                //这里默认高压和低压查出来的数量一样多
                for (int i = 0; i < list1.size(); i++) {
                    if (i <= 6) {
                        try {
                            xDayData.add(TimeUtils.millis2String(
                                    TimeUtils.string2Date(list1.get(i).getCL_TIME()).getTime(), "yyyy-MM-dd"));
                        } catch (Exception e) {
                            e.printStackTrace();
                            xDayData.add(list1.get(i).getCL_TIME() +"");
                        }
                        yDayData.add(list1.get(i).getCL_VALUE().replace("mmHg",""));
                        lDayData.add(list2.get(i).getCL_VALUE().replace("mmHg",""));
                    }
                }
                Collections.reverse(xDayData);
                Collections.reverse(yDayData);
                Collections.reverse(lDayData);
                LineData lineData = new LineData(setChartData(xDayData, yDayData,1,"高压(mmHg)"));
                lineData.addDataSet(setChartData(xDayData, lDayData,2,"低压(mmHg)"));
                lineChart.setData(lineData);
                lineChart.animateX(1000);
                lineChart.invalidate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        xDayData.add("2020-12-15");
//        xDayData.add("2020-12-16");
//        xDayData.add("2020-12-17");
//        xDayData.add("2020-12-18");
//        xDayData.add("2020-12-19");
//        xDayData.add("2020-12-20");
//        xDayData.add("2020-12-21");
//        yDayData.add("125");
//        yDayData.add("135");
//        yDayData.add("145");
//        yDayData.add("110");
//        yDayData.add("98");
//        yDayData.add("137");
//        yDayData.add("168");
//
//        lDayData.add("80");
//        lDayData.add("90");
//        lDayData.add("110");
//        lDayData.add("76");
//        lDayData.add("59");
//        lDayData.add("86");
//        lDayData.add("95");

    }

    /**
     * 为折线图设置数据，并且第一个图表的标签是日实时功率，后面的都是发电量，
     * 通过flag来判断,flag 0 实时功率 ，1  发电量
     * @param xData
     * @param yData
     */
    private LineDataSet setChartData(final List<String> xData , List<String> yData,int type,String name) {

        lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                int intValue = (int)value;
                if(xData.size()>intValue && intValue>=0){
                    //这样显示在X轴上值就是 05:30  05:35，不然会是1.0  2.0
                    return xData.get(intValue);
                }else{
                    return "";
                }
            }
        });

        lineChart.invalidate();

        MyMarkerView mv = new MyMarkerView(getActivity(), R.layout.custom_marker_view,xData);
        mv.setChartView(lineChart);
        lineChart.setMarker(mv);

        final ArrayList<Entry> values = new ArrayList<>();

        for (int i = 0; i < yData.size(); i++) {
            //注意这里的Entry（不一定需要）采用这种方式构造，采用其他的结果是一样的
            float y;
            try {
                y = Float.valueOf(yData.get(i));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                y = 0;
            }
            values.add(new Entry(i, y,xData.get(i)));
        }

        LineDataSet lineDataset ;

        if (lineChart.getData() != null && lineChart.getData().getDataSetCount() > 0) {
            lineDataset = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
            lineDataset.setDrawFilled(true);
            lineDataset.setFillDrawable(getResources().getDrawable(R.drawable.shape_line_gradiend_chart));
            lineDataset.setValues(values);
            lineDataset.setLabel(name);
            lineDataset.setDrawFilled(true);
            lineChart.getData().notifyDataChanged();
            lineChart.notifyDataSetChanged();
        }else{
            lineDataset = new LineDataSet(values, name);
            lineDataset.setDrawFilled(true);
            lineDataset.setDrawFilled(true);
            lineDataset.setFillDrawable(getResources().getDrawable(R.drawable.shape_line_gradiend_chart));
            int color = this.getResources().getColor(R.color.homecolor);
            if (type == 2) {
                color = this.getResources().getColor(R.color.man);
            }
            lineDataset.setColor(color);
            //设置是否显示圆点
            lineDataset.setDrawCircles(true);
            lineDataset.setValueTextColor(color);
            lineDataset.setCircleColor(color);
            lineDataset.setValueTextSize(10f);
            //是否显示每个点的Y值
            lineDataset.setDrawValues(true);
//            LineData lineData = new LineData(lineDataset);
//            lineData.addDataSet(lineDataset);
////            LineData lineData = new LineData(setLine(xDayData,yDayData,1,"高压"));
////            lineData.addDataSet(setLine(xDayData,lDayData,2,"低压"));
//            lineChart.setData(lineData);
//            lineChart.animateX(1000);

        }

        return lineDataset;
    }



    private LineDataSet setLine(List<String> xDayData,List<String> yDayData,int flag,String name) {
        ArrayList<String> xValsAge = new ArrayList<String>();
        for (int i = 0; i < xDayData.size(); i++) {
            xValsAge.add(xDayData.get(i));
        }
        ArrayList<Entry> yValsBabyTall = new ArrayList<Entry>();
        for (int i = 0; i < yDayData.size(); i++) {
            yValsBabyTall.add(new Entry(Float.parseFloat(yDayData.get(i)), i));
        }
        //设置baby的成长曲线
        LineDataSet setData = new LineDataSet(yValsBabyTall,name);
//        setData.setDrawCubic(true);  //设置曲线为圆滑的线
        setData.setCubicIntensity(0.2f);
        setData.setDrawFilled(false);  //设置包括的范围区域填充颜色
        setData.setDrawCircles(true);  //设置有圆点
        setData.setLineWidth(2f);    //设置线的宽度
        setData.setCircleSize(5f);   //设置小圆的大小
        setData.setHighLightColor(Color.rgb(244, 117, 117));
        //设置曲线颜色
        if(flag==1)
            setData.setColor(Color.rgb(104, 241, 175));    //宝宝身高曲线颜色
        else if(flag==2)
            setData.setColor(Color.rgb(255, 0, 0));    //普通身高曲线颜色
        return setData;    //返回曲线
    }

    private void initChartView() {
        //在点击高亮值时回调
        lineChart.setOnChartValueSelectedListener(this);

        //设置整个图表的颜色
        lineChart.setBackgroundResource(R.drawable.bg_line_chart);

        Legend l = lineChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);

        Description description = lineChart.getDescription();
        description.setYOffset(10);
        description.setEnabled(true);
        description.setText("时间");


        //是否可以缩放、移动、触摸
        lineChart.setTouchEnabled(true);
        lineChart.setDragEnabled(true);

        //不能让缩放，不然有bug，所以接口也没实现
        lineChart.setScaleEnabled(false);
        lineChart.setPinchZoom(true);

        //设置图表距离上下左右的距离
        lineChart.setExtraOffsets(10, 10, 10, 0);

        //获取左侧侧坐标轴
        YAxis leftAxis = lineChart.getAxisLeft();

        //设置是否显示Y轴的值
        leftAxis.setDrawLabels(true);
        leftAxis.setTextColor(this.getResources().getColor(R.color.color_8f8f));

        //设置所有垂直Y轴的的网格线是否显示
        leftAxis.setDrawGridLines(true);

        //设置虚线
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        leftAxis.setDrawZeroLine(false);

        //设置Y轴最大值最小值，如果不设置取数据里面的值，如果设置则按照设置的值
//        leftAxis.setAxisMinimum(180f);
//        leftAxis.setAxisMinimum(40f);
//        leftAxis.setAxisMaxValue(180f);
//        leftAxis.setAxisMinValue(40f);

        //将右边那条线隐藏
        lineChart.getAxisRight().setEnabled(false);
        //获取X轴
        XAxis xAxis = lineChart.getXAxis();
        //设置X轴的位置，可上可下
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置x轴间距
        xAxis.setGranularity(0.9f);

        //将垂直于X轴的网格线隐藏，将X轴显示
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(true);

        //设置X轴上lable颜色和大小
        xAxis.setTextSize(8f);
        xAxis.setTextColor(Color.GRAY);

        //设置X轴高度
        xAxis.setAxisLineWidth(1);
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

}
